package com.liaoban.app.api.manager;

import android.content.Context;
import android.text.TextUtils;

import com.liaoban.app.App;
import com.liaoban.app.R;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ConfigKey;
import com.liaoban.app.constants.HttpConstant;
import com.liaoban.app.converter.GsonConverterFactory;
import com.liaoban.app.exception.AppException;
import com.liaoban.app.helper.ConfigHelper;
import com.liaoban.app.util.NetUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * retrofit的管理类
 * Created by ybc on 2017/7/4.
 */

public class HttpManager {
    private static final HttpManager ourInstance = new HttpManager();

    public static HttpManager getInstance() {
        return ourInstance;
    }

    private HttpApi mHttpApi;

    private HttpManager() {
    }

    public void init(Context context, String env) {
        switch (env) {
            case HttpConstant.HTTP_API_ENV_LUCK:
                initApi(context, new HttpConstant.LuckEnv());
                break;
            case HttpConstant.HTTP_API_ENV_RELEASE:
                initApi(context, new HttpConstant.ReleaseEnv());
                break;
            case HttpConstant.HTTP_API_ENV_DEV:
            default:
                initApi(context, new HttpConstant.DevEnv());
                break;
        }
    }

    private void initApi(Context context, HttpConstant.Env env) {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(chain -> {
            //当没有网络连接时
            if (!NetUtil.isConnected(App.getInstance().getApplicationContext())) {
                throw AppException.createCustomAppException(AppException.NONE_NETWORK_CODE, context.getString(R.string.none_network));
            }
            Request original = chain.request();
            Request.Builder builder = original.newBuilder();
            builder.addHeader("Content-Type", "application/json; charset=UTF-8");
            if(CommonBiz.getInstance().isLogin(context)) {
                String token = ConfigHelper.getString(context, ConfigKey.TOKEN);
                if(!TextUtils.isEmpty(token)) {
                    builder.addHeader("token", token);
                }
            } else {
                builder.addHeader("token", "20YldGdmJXRnZaR0U917");
            }

            //builder.addHeader("version_code", String.valueOf(CommonUtils.getVersionCode(App.getInstance().getApplicationContext())));
            //builder.addHeader("platform", "android");
            Request request = builder.method(original.method(), original.body()).build();
            Response response = chain.proceed(request);
            return response;
        });
        httpClient.connectTimeout(HttpConstant.CONNECT_TIME_OUT, TimeUnit.SECONDS);
        httpClient.readTimeout(HttpConstant.READ_TIME_OUT, TimeUnit.SECONDS);
        httpClient.writeTimeout(HttpConstant.WRITE_TIME_OUT, TimeUnit.SECONDS);

        // 添加日志输出
        HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
        logger.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.addInterceptor(logger);

        Retrofit retrofit = new Retrofit.Builder()
                .client(httpClient.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(env.apiBaseUrl)
                .build();
        mHttpApi = retrofit.create(HttpApi.class);
    }

    public HttpApi getHttpApi() {
        return mHttpApi;
    }
}
